package com.videoaggre.zcl.ui.activity.wallpaper.meizuo

import android.content.Context
import android.os.Build
import android.os.Environment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewpager.widget.PagerAdapter
import com.bumptech.glide.Glide
import com.kingja.loadsir.core.LoadService
import com.videoaggre.zcl.R
import com.videoaggre.zcl.api.ApiObserver
import com.videoaggre.zcl.api.MEIZUO_SERVICE
import com.videoaggre.zcl.bean.EnterdeskImage
import com.videoaggre.zcl.bean.MeizuoImage
import com.videoaggre.zcl.common.*
import com.videoaggre.zcl.databinding.MeizuoItemImageBinding
import com.videoaggre.zcl.helper.InjectBundle
import com.videoaggre.zcl.helper.loadsir.LoadSirHelper
import com.videoaggre.zcl.parse.impl.MeizuoParse
import com.videoaggre.zcl.ui.activity.BaseActivity
import com.videoaggre.zcl.ui.activity.launchUI
import com.videoaggre.zcl.ui.adapter.BaseRecyclerAdapter
import com.videoaggre.zcl.ui.adapter.BaseViewHolder
import com.videoaggre.zcl.ui.dialog.showAlertDialog
import com.videoaggre.zcl.utils.AlbumUtils
import com.videoaggre.zcl.utils.SPUtils
import com.yanzhenjie.album.widget.photoview.PhotoViewAttacher
import com.yanzhenjie.permission.runtime.Permission
import com.yanzhenjie.sofia.Utils
import kotlinx.android.synthetic.main.meizuo_activity_image_detail.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class MeizuoImageDetailActivity : BaseActivity(R.layout.meizuo_activity_image_detail) {
    private val mLoadService: LoadService<*> by lazy { LoadSirHelper.register(rootView) { onReload() } }
    private val mEnterdeskImage: EnterdeskImage by InjectBundle()
    private var previewList: MutableList<MeizuoImage>? = null
    override fun initView() {
        Utils.invasionStatusBar(this)
        Utils.invasionNavigationBar(this)
        bindViewClick(ivClose, buttonSaveAlbum)
    }

    override fun initData() {
        mLoadService.showLoadingCallback()
        onReload()
    }

    private fun onReload() {
        if (SPUtils.getBoolean(SP_KEY_MEIZUO_IMAGE_DETAIL_SHOW, true)) {
            showAlertDialog {
                message(message = "图片资源较多耐心等待")
                negativeButton(name = "不再提示") { SPUtils.put(SP_KEY_MEIZUO_IMAGE_DETAIL_SHOW, false) }
                positiveButton(name = "我知道了") {}
            }
        }
        launchUI({
            // 获取第一页可以知道总共多少页
            val meizuoImages = mutableListOf<MeizuoImage>()
            var firstMeizuoImage = MeizuoParse.parseDetailImage(MEIZUO_SERVICE.meizuoMobileDetail(mEnterdeskImage.detailId, 1))
            meizuoImages.add(firstMeizuoImage)
            load(firstMeizuoImage.url)
            for (index in 2..firstMeizuoImage.totalPage) {
                firstMeizuoImage = MeizuoParse.parseDetailImage(MEIZUO_SERVICE.meizuoMobileDetail(mEnterdeskImage.detailId, index))
                meizuoImages.add(firstMeizuoImage)
                load(firstMeizuoImage.url)
            }
            meizuoImages
        }, ApiObserver(loadService = mLoadService) {
            if (it != null) {
                previewList = it
                viewPager.adapter = PreviewAdapter(this, it)
            }
        })
    }

    override fun onClick(v: View?) {
        when (v) {
            ivClose -> finish()
            buttonSaveAlbum -> {
                previewList?.get(viewPager.currentItem)?.apply {
                    showAlertDialog {
                        message(message = "确定保存到相册吗?")
                        negativeButton { }
                        positiveButton {
                            if (Build.VERSION.SDK_INT < 29 || Environment.isExternalStorageLegacy()) {
                                permissionRequest {
                                    permission(Permission.WRITE_EXTERNAL_STORAGE)
                                    onGranted { saveBitmap(url) }
                                    onDenied { "未授权无法保存".toastMessageLong() }
                                }
                            } else {
                                saveBitmap(url)
                            }
                        }
                    }
                }
            }
        }
    }

    private fun saveBitmap(url: String) {
        buttonSaveAlbum.enable(false)
        launchUI({
            AlbumUtils.saveBitmap(this@MeizuoImageDetailActivity, load(url), "${System.currentTimeMillis()}.png")
        }, ApiObserver(complete = { buttonSaveAlbum.enable(true) }) {
            "保存成功,请去相册查看".toastMessageLong()
        })
    }

    private suspend fun load(url: String) = withContext(Dispatchers.IO) {
        Glide.with(this@MeizuoImageDetailActivity)
            .asFile()
            .load(url)
            .submit()
            .get()
    }

    class PreviewAdapter(private val context: Context, private val previewList: MutableList<MeizuoImage>) : PagerAdapter() {
        override fun getCount() = previewList.size
        override fun isViewFromObject(view: View, obj: Any) = view == obj
        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            val binding = MeizuoItemImageBinding.inflate(LayoutInflater.from(context))
            Glide.with(binding.ivImage.context)
                .load(previewList[position].url)
                .into(binding.ivImage)
            container.addView(binding.ivImage)
            binding.ivImage.setAttacher(PhotoViewAttacher(binding.ivImage))
            return binding.ivImage
        }

        override fun destroyItem(container: ViewGroup, position: Int, obj: Any) {
            container.removeView(obj as View?)
        }
    }

    class MeizuoImageDetailAdapter : BaseRecyclerAdapter<BaseViewHolder<MeizuoItemImageBinding>, MeizuoImage>() {
        override fun onCreateViewHolder(parent: ViewGroup, p1: Int) = BaseViewHolder(MeizuoItemImageBinding.inflate(getLayoutInflate(parent.context), parent, false))
        override fun onBindViewHolder(holder: BaseViewHolder<MeizuoItemImageBinding>, bean: MeizuoImage, position: Int) {
            holder.mViewBinding.apply {
                bean.apply {
                    //val placeholder = GlideUtils.getBackgroundColor()
                    Glide.with(ivImage.context)
                        .load(url)
                        //.transition(GenericTransitionOptions.with(R.anim.zoom_in))
                        //.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                        //.placeholder(placeholder)
                        //.error(placeholder)
                        .into(ivImage)
                    setViewClick(position, root)
                }
            }
        }
    }
}